package com.fand.context;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 上下文持有
 * 
 * @author yaoHT
 * 
 */
public class ContextHolder implements ApplicationContextAware {
	/**
	 * Spring ApplicationContext
	 */
	private static ApplicationContext applicationContext;

	/**
	 * 标识
	 */
	private static final ThreadLocal<String> idThreadLocal = new ThreadLocal<String>();

	/**
	 * 字符串映射
	 */
	private static final ThreadLocal<Map<String, String>> stringMapThreadLocal = new ThreadLocal<Map<String, String>>();

	public static void clearId() {
		ContextHolder.idThreadLocal.remove();
	}

	public static void clearStringValue() {
		ContextHolder.stringMapThreadLocal.remove();
	}

	public static ApplicationContext getApplicationContext() {
		return ContextHolder.applicationContext;
	}

	public static <T> T getBean(final Class<T> requiredType) {
		if (ContextHolder.applicationContext.containsBean(requiredType.getName())) {
			return ContextHolder.applicationContext.getBean(requiredType.getName(), requiredType);
		}

		return ContextHolder.applicationContext.getBean(requiredType);
	}

	public static String getId() {
		return ContextHolder.idThreadLocal.get();
	}

	public static String getStringValue(final String key) {
		if (ContextHolder.stringMapThreadLocal.get() == null) {
			return null;
		}

		return ContextHolder.stringMapThreadLocal.get().get(key);
	}

	public static void setId(final String value) {
		ContextHolder.idThreadLocal.set(value);

	}

	public static void setStringValue(final String key, final String value) {
		if (ContextHolder.stringMapThreadLocal.get() == null) {
			ContextHolder.stringMapThreadLocal.set(new HashMap<String, String>());
		}

		ContextHolder.stringMapThreadLocal.get().put(key, value);
	}

	@Override
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
		ContextHolder.applicationContext = applicationContext;
	}
}
